<?php
/**
 * Created by PhpStorm.
 * User: Xwen
 * Date: 2018/12/11
 * Time: 23:10
 *
 *          ┌─┐       ┌─┐
 *       ┌──┘ ┴───────┘ ┴──┐
 *       │                 │
 *       │       ───       │
 *       │  ─┬┘       └┬─  │
 *       │                 │
 *       │       ─┴─       │
 *       │                 │
 *       └───┐         ┌───┘
 *           │         │
 *           │         │
 *           │         │
 *           │         └──────────────┐
 *           │                        │
 *           │                        ├─┐
 *           │                        ┌─┘
 *           │                        │
 *           └─┐  ┐  ┌───────┬──┐  ┌──┘
 *             │ ─┤ ─┤       │ ─┤ ─┤
 *             └──┴──┘       └──┴──┘
 *                 神兽保佑
 *                 代码无BUG!
 *"The trouble with programmers is that you can never tell what a programmer is doing until it’s too late.”- Seymour Cray
 */
namespace app\admin\logic;
use app\admin\validate\Role as RoleValidate;
use think\Db;
use think\Session;

class Role
{
    public function infos($pageNumber, $pageSize, $name = NULL){
        $where[] = ['is_delete', '=', 0];
        if($name != NULL){
            $where[] = ['role_name', 'LIKE', '%'.$name.'%'];
        }
        $data = model("Role")->getPage($where, $pageNumber, $pageSize);
        $count = model("Role")->getCount($where);

        return [
            'total'      =>         $count,
            'rows'       =>         $data,
        ];
    }
    public function add($data){
        $validate = new RoleValidate();
        $result = $validate->scene('add')->check($data);
        if (!$result) {
            exception($validate->getError());
        }
        $adminName = (new Session())->get('USER_INFO.userName');
        $info['creator'] = $adminName;
        $info['updater'] = $adminName;
        $info['create_time'] = time();
        $info['update_time'] = time();

        $role_data['role_name'] = $data['role_name'];
        $role_data = array_merge($role_data, $info);
        Db::startTrans();
        try{
            $role_id = model('Role')->insertGetId($role_data);
            if(!empty($data['permission_ids'])){
                $rpData = array();
                foreach ($data['permission_ids'] as $k => $v) {
                    $rpData[$k]['permission_id'] = $v;
                    $rpData[$k]['role_id'] = $role_id;
                    $rpData[$k] = array_merge($rpData[$k], $info);
                }
                model('RolePermission')->insertAll($rpData);
            }
            Db::commit();
            return true;
        } catch(\Exception $e) {
            Db::rollback();
            return false;
        }
    }
    public function edit($data){
        $validate = new RoleValidate();
        $result = $validate->scene('edit')->check($data);
        if (!$result) {
            exception($validate->getError());
        }

        Db::startTrans();
        try {
            $adminName = (new Session())->get('USER_INFO.userName');
            $info['creator'] = $adminName;
            $info['create_time'] = time();
            $infos['updater'] = $adminName;
            $infos['update_time'] = time();

            $roleWhere[] = ['is_delete', 'eq', 0];
            $roleWhere[] = ['id', 'eq', $data['id']];
            model('Role')->where($roleWhere)->update([
                'role_name'         =>  $data['role_name'],
                'updater'           =>  $adminName,
                'update_time'       =>  time()
            ]);

            $where[] = ['is_delete', 'eq', 0];
            $where[] = ['role_id', 'eq', $data['id']];
            $dData = [
                'is_delete'     =>  1
            ];
            if(!empty($data['permission_ids'])){
                $role_permission = model('RolePermission')->where($where)->field('permission_id')->select()->toArray();
                $role_permission = array_column($role_permission, 'permission_id');
                // 提交的数据相对之前数据的差集（需禁用项）
                $role_permission_delete = array_diff($role_permission, $data['permission_ids']);
                model('RolePermission')->where($where)->whereIn('permission_id', $role_permission_delete)->update(array_merge($infos, $dData));
                // 之前数据相对提交的数据的差集（需添加项）
                $role_permission_add = array_diff($data['permission_ids'], $role_permission);
                $rpData = array();
                foreach ($role_permission_add as $k => $v) {
                    $rpData[$k]['permission_id'] = $v;
                    $rpData[$k]['role_id'] = $data['id'];
                    $rpData[$k] = array_merge(array_merge($rpData[$k], $info), $infos);
                }
                model('RolePermission')->insertAll($rpData);
            }else{
                model('RolePermission')->where($where)->update(array_merge($infos, $dData));
            }
            Db::commit();
            return true;
        } catch(\Exception $e) {
            Db::rollback();
            return false;
        }

    }
    public function delete($data){
        $validate = new RoleValidate();
        $result = $validate->scene('delete')->check($data);
        if (!$result) {
            exception($validate->getError());
        }
        Db::startTrans();
        try {
            $adminName = (new Session())->get('USER_INFO.userName');
            $info['updater'] = $adminName;
            $info['update_time'] = time();
            $info['is_delete'] = 1;

            model('Role')->where('id', 'eq', $data['id'])->update($info);
            model('RolePermission')->where('role_id', 'eq', $data['id'])->update($info);
            Db::commit();
            return true;
        } catch (\Exception $e){
            Db::rollback();
            return false;
        }
    }
    public function getAll(){
        return model('Role')->where('is_delete', 'eq', 0)->field('id,role_name')->select()->toArray();
    }
    public function getAllWithUserEdit($data){
        $validate = new RoleValidate();
        $result = $validate->scene('delete')->check($data);
        if (!$result) {
            exception($validate->getError());
        }
        $role = model('Role')->where('is_delete', 'eq', 0)->field('id,role_name')->select()->toArray();
        $user_role = model('UserRole')->where('is_delete', 'eq', 0)
            ->where('user_id', 'eq', $data['id'])->field('role_id')->select()->toArray();
        $user_role = array_column($user_role, 'role_id');
        foreach ($role as $k => $v) {
            $role[$k]['selected'] = false;
            if (in_array($v['id'], $user_role)) {
                $role[$k]['selected'] = true;
            }
        }
        return $role;
    }

}